package com.sheng.leetcode.year2024.month01.day15;

import org.junit.Test;

/**
 * @author by ls
 * @date 2024/1/15
 * <p>
 * 82. 删除排序链表中的重复元素 II<p>
 * <p>
 * 给定一个已排序的链表的头 head ， 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表 。<p>
 * <p>
 * 示例 1：<p>
 * 输入：head = [1,2,3,3,4,4,5]<p>
 * 输出：[1,2,5]<p>
 * <p>
 * 示例 2：<p>
 * 输入：head = [1,1,1,2,3]<p>
 * 输出：[2,3]<p>
 * <p>
 * 提示：<p>
 * 链表中节点数目在范围 [0, 300] 内<p>
 * -100 <= Node.val <= 100<p>
 * 题目数据保证链表已经按升序 排列<p>
 */
public class LeetCode0082 {

    @Test
    public void test01() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(3, new ListNode(3, new ListNode(4, new ListNode(5)))))));
//        ListNode head = new ListNode(1, new ListNode(1, new ListNode(2, new ListNode(2))));
        ListNode listNode = new Solution().deleteDuplicates(head);
        System.out.println(listNode);
//        String key = "RyrHLDNP5EAanxwCXiKv5Q==";
//        String content = "47/mG7M+IqJR1gA3w38naA==";
//        byte[] decrypt = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).decrypt(Base64.decode(content));
//        System.out.println(new String(decrypt));
    }
}

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode listNode = new ListNode(0, head);
        // 前一个节点
        ListNode preNode = listNode;
        // 当前节点
        ListNode node = head;
        while (node != null) {
            while (node.next != null && node.next.val == node.val) {
                node = node.next;
            }
            if (preNode.next == node) {
                preNode = node;
            } else {
                preNode.next = node.next;
            }
            node = node.next;
        }
        return listNode.next;
    }
}

// Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
